package com.jkl.nettyserver.Netty;

import com.jkl.nettyserver.Config.NettyConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

@Slf4j
@Component
public class NettyServer {
    final NettyConfig nettyConfig;
    final EventLoopGroup bossGroup;
    final EventLoopGroup workerGroup;
    final NettyServerChannelInitializer nettyServerChannelInitializer;
    @Autowired
    public NettyServer(NettyConfig nettyConfig, NettyServerChannelInitializer nettyServerChannelInitializer) {
        this.nettyConfig = nettyConfig;
        bossGroup = nettyConfig.bossGroup();
        workerGroup = nettyConfig.workerGroup();
        this.nettyServerChannelInitializer = nettyServerChannelInitializer;
    }
    public void start() throws UnknownHostException {//服务端启动器，监听客户端连接
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                // 指定使用的线程组
                .group(bossGroup,workerGroup)
                // 选择 服务器的ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)// OIO BIO
                .handler(new LoggingHandler(LogLevel.INFO))
                .localAddress(new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(),nettyConfig.getPort()))
                //快速复用端口
                .childOption(ChannelOption.SO_REUSEADDR, true)
                // 指定连接超时时间
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyConfig.getTimeout())
                // 指定worker（child）处理器，负责处理读写，决定worker(child)能执行哪些操作（handle)
                .childHandler(nettyServerChannelInitializer);
        //绑定端口
        try{
            ChannelFuture channelFuture = serverBootstrap.bind().sync();//异步绑定管道
            log.info("Server started and listen on:{}", channelFuture.channel().localAddress());
            channelFuture.channel().closeFuture().sync();//异步删除管道
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}